﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BooksOnline.Models.Entities;
using BooksOnline.Repositories.Base;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace BooksOnline.Tests
{
    public class FixtureBase<T>
    {
        protected static ISessionFactory sessionFactory;
        protected static ISession session;

        protected static ISession Session
        {
            get
            {
                if(session == null)
                {
                    session = CreateSession();
                }
                return session;
            }
            set
            {
                session = value;
            }
        }

        protected static Configuration configuration;

        protected virtual void SetUp()
        {
            NHibernateSessionProvider.CurrentSession = Session;
        }

        private static ISessionFactory CreateSessionFactory()
        {
            sessionFactory =
                Fluently
                    .Configure()
                    .Database(SQLiteConfiguration
                                  .Standard
                                  .InMemory()
                                  .ShowSql())
                    .Mappings(a => a.FluentMappings.AddFromAssemblyOf<Book>())
                    .ExposeConfiguration(c => configuration = c)
                    .BuildSessionFactory();

            NHibernateSessionProvider.SetSessionFactory(sessionFactory); 

            return sessionFactory;
        }

        private static void BuildSchema(ISession Session)
        {
            SchemaExport export = new SchemaExport(configuration);
            export.Execute(true, true, false, session.Connection, null);
        }

        private static ISession CreateSession()
        {
            ISessionFactory sessionFactory = CreateSessionFactory();
            session = sessionFactory.OpenSession();
            BuildSchema(session);
            return session;
        }
    }
}
